package cn.krui.project.service.system;

import cn.krui.helper.bean.DataSingle;
import cn.krui.helper.db.DBHelper;
import cn.krui.helper.db.SQL;
import cn.krui.project.bean.system.sys_dept.sys_dept;
import cn.krui.project.controller.system.SystemBase;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
 

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: project-system
 * @description: 部门模块
 * @author: zc
 * @create: 2019-10-11 10:57
 **/
@Service
public class SysDeptService extends SystemBase {

	@Autowired
	private DBHelper dbHelper;

	/**
	 * 系统部门查询
	 */
	public List<sys_dept> selectSysDeptList(DataSingle<sys_dept> sysDept) {
		SQL.SelectSQL sql = SQL.select("*").from("qr_sys_dept").where("pid=0");
		Map<String, Object> where = new HashMap<>(10);
		if (!StringUtils.isEmpty(sysDept.getDataSingle().getDept_name())) {
			sql.where("dept_name like '%#{dept_name}%'");
			where.put("dept_name", sysDept.getDataSingle().getDept_name());
		}
		if (sysDept.getDataSingle().getLevel() != null) {
			sql.where("level =#{level}");
			where.put("level", sysDept.getDataSingle().getLevel());
		}
		if (!StringUtils.isEmpty(sysDept.getDataSingle().getDept_pro())) {
			sql.where("dept_pro =#{dept_pro}");
			where.put("dept_pro", sysDept.getDataSingle().getDept_pro());
		}
		if (!StringUtils.isEmpty(sysDept.getDataSingle().getDept_city())) {
			sql.where("dept_city =#{dept_city}");
			where.put("dept_city", sysDept.getDataSingle().getDept_city());
		}
		if (!StringUtils.isEmpty(sysDept.getDataSingle().getDept_addr())) {
			sql.where("dept_addr = #{dept_addr}");
			where.put("dept_addr", sysDept.getDataSingle().getDept_addr());
		}
		sql.where("group_id = #{group_id}");
		where.put("group_id", getUser().getUid());
		if (sysDept.getExtend() != null) {
			Map<String, Object> o = dbHelper.selectOne("group_id", "qr_sys_users",
					"id=" + sysDept.getExtend().toString(), null);
			where.put("group_id", o.get("group_id"));
		}
		sql.orderBy("sort desc");
		List<sys_dept> sysRolesList = dbHelper.select(sql, where, sys_dept.class);
		where.clear();
		return sysRolesList;
	}

	/**
	 * 添加系统部门
	 * 
	 * @param sysDept
	 * @return
	 */
	public Integer addSysDept(sys_dept sysDept) {
		Object i = dbHelper.insert("qr_sys_dept", sysDept, sys_dept.class);
		return Integer.valueOf(i.toString());
	}

	/**
	 * 更新系统部门
	 * 
	 * @return
	 */
	public Integer updateSysDept(sys_dept sysDept) {
		int i = dbHelper.update("qr_sys_dept", sysDept, sys_dept.class, "id=#{id}");
		return i;
	}

	/**
	 * 删除系统部门
	 * 
	 * @return
	 */
	public Integer deleteSysDept(String id) {
		SQL.DeleteSQL sql = SQL.delete("qr_sys_dept").where("id=#{id}").addParameter("id", id);
		int i = dbHelper.delete(sql);
		return i;
	}

}
